package com.nexgo.payment.trans.scanpreauthcom;

import android.support.annotation.NonNull;

import com.nexgo.data.entity.RecvData;
import com.nexgo.oaf.apiv3.emv.EmvAlgorithmTypeEnum;
import com.nexgo.oaf.apiv3.emv.EmvChannelTypeEnum;
import com.nexgo.oaf.apiv3.emv.EmvProcessResultEntity;
import com.nexgo.oaf.apiv3.emv.EmvTransDataEntity;
import com.nexgo.oaf.apiv3.emv.EmvTransFlowEnum;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.action.ActionResult;
import com.nexgo.payment.action.ActionStep;
import com.nexgo.payment.aop.annotation.TransCondition;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.SysConstant;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.trans.AbsTransPresenter;
import com.nexgo.payment.trans.TransFlow;
import com.nexgo.payment.util.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 扫码预授权完成
 * Created by 谢豪景 on 2017/10/24.
 */
@TransCondition
@TransFlow(checkFreePinBySetting = true)
public class ScanPreAuthComPresenter extends AbsTransPresenter implements ScanPreAuthComContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(ScanPreAuthComPresenter.class.getSimpleName());

    private ScanPreAuthComContract.View mView;
    private ScanState mScanState = ScanState.INIT_SCAN;
    public ScanPreAuthComPresenter(@NonNull ScanPreAuthComContract.View view, @NonNull DataSource repository) {
        super(view, repository);
        mView = checkNotNull(view);
        mView.setPresenter(this);
    }
    @Override
    public void start() {
        super.start();
        onScanNextToOnline();
    }

    /**
     * 扫码后下一步动作
     *
     * @param data
     */
    public void inputScanNext(Object data) {
        mLog.debug("扫码得到的数据：{}",data);

        String orgauthcode = data.toString().substring(0, 6);
        mLog.debug("原交易授权码：{}",orgauthcode);

        String orgdate = data.toString().substring(6, 11);
        mLog.debug("原交易日期：{}",orgdate);

        String expdate = data.toString().substring(10, 14);
        mLog.debug("卡片有效期：{}",expdate);

        String pan = data.toString().substring(14);
        mLog.debug("卡号：{}",pan);

        mTransData.setOrgAuthCode(orgauthcode);
        mTransData.setOrgDate(orgdate);
        mTransData.setExpDate(expdate);
        mTransData.setPan(pan);
        mScanState = ScanState.END_SCAN; //记录扫码后的状态

    }

    @Override
    protected TransData getTransData() {
        TransData transData = new TransData();
        transData.setTransType(TransType.AUTH_CM);
        return transData;
    }

    @Override
    protected EmvTransDataEntity getEmvTransData(EmvChannelTypeEnum channelType) {
        EmvTransDataEntity emvTransData = new EmvTransDataEntity();
        emvTransData.setChannelType(channelType);
        emvTransData.setB9C((byte) 0x00);
        emvTransData.setTransAmt(mTransData.getAmount());
        emvTransData.setTermId(mRepository.getParamValue(PreferencesConstants.TERMINAL_ID));
        emvTransData.setMerId(mRepository.getParamValue(PreferencesConstants.MERCHANT_ID));
        emvTransData.setMerName(mRepository.getParamValue(PreferencesConstants.MERCHANT_NAME));
        emvTransData.setTransDate(new SimpleDateFormat("yyMMdd", SysConstant.LOCALE).format(new Date()));
        emvTransData.setTransTime(new SimpleDateFormat("hhmmss", SysConstant.LOCALE).format(new Date()));
        emvTransData.setTraceNo(mRepository.getParamValue(PreferencesConstants.TRACE_NUMBER));
        emvTransData.setAlgType("1".equals(mRepository.getParamValue(PreferencesConstants.EMV_SUPPORT_SM2)) ?
                EmvAlgorithmTypeEnum.SM2 : EmvAlgorithmTypeEnum.RSA);
        if (channelType == EmvChannelTypeEnum.FROM_PICC) {
            emvTransData.setProcType(EmvTransFlowEnum.QPASS);
            emvTransData.setIsForceOnline(true);
        } else {
            emvTransData.setProcType(EmvTransFlowEnum.SIMPLE);
            emvTransData.setChannelType(EmvChannelTypeEnum.FROM_ICC);
        }
        return emvTransData;
    }

    @Override
    protected void onFirstAction() {
        postMainThread(() -> mView.showInputAmount(mTransData));


    }
    @Override
    protected void inputAmountNext(Object data) {
        mLog.debug("金额：{}",data.toString());
        mTransData.setAmount(StringUtils.leftPad((String) data, 12, '0'));
        //调用输入扫码界面
        mScanState = ScanState.START_SCAN;
        postMainThread(() -> mView.showScanFragment());
    }
    @Override
    public void importActionResult(ActionResult actionResult) {
        Object data = actionResult.getData();
        ActionStep step = (ActionStep) actionResult.getAction().getActionStep();
        int ret = actionResult.getRet();
        mLog.debug("curr action step {} ret {}", step, actionResult.getRet());
        //成功处理进行处理，否则让父类处理
        if (ret == ActionResult.SUCC) {
            switch (step) {
                /*case INPUT_AMOUNT:
                    inputAmountNext(data);
                    break;*/
                case INPUT_SCAN:
                    inputScanNext(data);
                    break;
                default:
                    break;
            }
        }
        super.importActionResult(actionResult);
    }
    @Override
    protected void onTransSuccess(RecvData recvData, EmvProcessResultEntity emvResult) {
        mScanState = ScanState.FINISH;
        postMainThread(() -> mView.quitTrans());
    }

    @Override
    public void onScanNextToOnline() {
        if (mScanState == null || mScanState == ScanState.INIT_SCAN) return;
        mLog.debug("扫码状态：{}", mScanState);
        if (mScanState != null && mScanState == ScanState.END_SCAN){
            mScanState = ScanState.ONLINE; //联机
            postMainThread(() -> mView.showOnlineProc(mTransData,null));
            return;
        }
        postMainThread(() -> mView.showError(App.sContext.getString(R.string.trans_fail)));

    }

    /**
     * 扫码状态
     */
    enum ScanState{
        INIT_SCAN,   //初始化
        START_SCAN,  //开始扫码
        END_SCAN,    //结束扫码
        ONLINE,      //联机
        FINISH       //交易结束
    }
}
